Day 10 - Function with output & Calculator


Posted by pei_______ on 2022-04-20

learning from 100 Days of Code: The Complete Python Pro Bootcamp for 2022


# Format name

def format_name(f_name,l_name):
  """Take a first and last name and format it 
  to return the title case version of the name."""

  if f_name == "" or l_name == "":
    return "You didn't provide a valid inputs."
    ## 只要遇到return就會強制結束函式

  format_f_name = f_name.title()
  format_l_name = l_name.title()
  return f"{format_f_name} {format_l_name}"

print(format_name("PENNY","lee"))

# Days in Month

def is_leap(year):
  if year % 4 == 0:
    if year % 100 == 0:
      if year % 400 == 0:
        return True
      else:
        return False
    else:
      return True
  else:
    return False

def days_in_month(year, month):
  month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]  
  if is_leap(year) and month ==2:
    return 29
  else :
    return month_days[month - 1]

year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
days = days_in_month(year, month)
print(days)

# calculator

from replit import clear
from art import logo

def add(n1,n2):
  return n1 + n2

def subtract(n1,n2):
  return n1 - n2

def multiply(n1,n2):
  return n1 * n2

def divide(n1,n2):
  return n1 / n2

operations ={
  "+" : add,
  "-" : subtract,
  "*" : multiply,
  "/" : divide,
}


def calculator():
  print(logo)
  num1 = float(input("What's the first number?: "))
  continue_calculate = True

  for symbol in operations:
    print (symbol)

  while continue_calculate:
    operations_symbol = input("Pick an operation: ")
    num2 = float(input("What's the next number?: "))
    calculator_function = operations[operations_symbol]
    answer = calculator_function(num1,num2)

    print(f"{num1} {operations_symbol} {num2} = {answer}")
    num1 = answer

    if input(f"Type 'y' to continue calculating with {answer}, or type'n' to exit: ") == "n":
      continue_calculate = False
      clear()
      calculator()

calculator()

#Python #課堂筆記 #100 Days of Code







Related Posts

Speech Synthesis

Speech Synthesis

Secure Apache Using Certbot with Let's Encrypt on Ubuntu 20.04

Secure Apache Using Certbot with Let's Encrypt on Ubuntu 20.04

開平春遊

開平春遊


Comments